<template>
  <div class="snow-page">
    <a-layout>
      <a-layout-sider style="min-width: 250px;">
        <div>
          <h4 style="margin: 10px">企业列表

            <a-input v-model="serachValue" style="width:180px" placeholder="关键字搜索" allow-clear />
            <a-button type="primary" @click="InputEvent">
              <template #icon>
                <icon-search />
              </template>
            </a-button>
          </h4>
          <a-tree :data="treeNodes" :field-names="{
            key: 'id',
            title: 'name',
            children: 'children'
          }" @select="clickTreeNode" style="margin-left: 5px;max-height: 100vh;overflow: auto;">
            <template #title="{ name }">
              <a-tooltip :content="name">
                <div class="marquee">
                  <icon-common />
                  {{ name }}
                </div>
              </a-tooltip>
            </template>
          </a-tree>
        </div>
      </a-layout-sider>
      <a-layout>
        <a-layout-content>
          <div class="snow-inner-page">
            <a-form :model="formData.form" :label-col-props="{ span: 5 }" :wrapper-col-props="{ span: 18 }"
              ref="formRef">
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item field="name" label="名称">
                    <a-input v-model="formData.form.name" placeholder="请输入名称" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-space>
                    <a-button type="primary" @click="onSearch">
                      <template #icon>
                        <icon-search />
                      </template>
                      <template #default>查询</template>
                    </a-button>
                    <a-button @click="onReset">
                      <template #icon>
                        <icon-refresh />
                      </template>
                      <template #default>重置</template>
                    </a-button>
                    <a-button type="primary" @click="onAdd">
                      <template #icon>
                        <icon-PlusOutlined />
                      </template>
                      <template #default>新增</template>
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
            <a-table :data="tableData" row-key="id" :pagination="false">
              <template #columns>
                <a-table-column title="网关编码" :width="180">
                  <template #cell="{ record }">
                    {{ record.cq_equip_code }}
                  </template>
                </a-table-column>
                <a-table-column title="企业名称" :width="280">
                  <template #cell="{ record }">
                    {{ formatqiye(record.scene_id) }}
                  </template>
                </a-table-column>

                <a-table-column title="网关号" :width="120">
                  <template #cell="{ record }">
                    {{ record.device_code }}
                  </template>
                </a-table-column>
                <a-table-column title="网关名称" :width="120">
                  <template #cell="{ record }">
                    {{ record.name }}
                  </template>
                </a-table-column>

                <a-table-column title="网关类型" :width="120">
                  <template #cell="{ record }">
                    {{ format558(record.cq_equip_type) }}
                  </template>
                </a-table-column>

                <a-table-column title="运行状态" :width="120">
                  <template #cell="{ record }">
                    <a-tag color="arcoblue" v-if="record.data.iot_node_status == '在线'">{{ record.data.iot_node_status
                      }}</a-tag>
                    <a-tag color="red" v-else>{{ record.data.iot_node_status }}</a-tag>
                  </template>
                </a-table-column>
                <a-table-column title="网关描述" :width="180">
                  <template #cell="{ record }">
                    {{ record.infos }}
                  </template>
                </a-table-column>

                <a-table-column title="操作" align="center" fixed="right">
                  <template #cell="{ record }">
                    <a-space>
                      <a-button size="mini" type="primary" @click="onEdit(record)">修改</a-button>
                      <a-button size="mini" type="primary" @click="clickName(record)">详情</a-button>
                      <a-button size="mini" type="primary" status="danger" @click="onDelete2(record)">删除</a-button>
                      <a-dropdown trigger="hover">
                        <a-button>更多</a-button>
                        <template #content>
                          <a-doption value="0" @click="projectshuxSet(record)">属性设置</a-doption>
                        </template>
                      </a-dropdown>
                    </a-space>
                  </template>
                </a-table-column>
              </template>
            </a-table>
            <a-pagination :total="total" style="margin-top: 10px" @change="changePage" />
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </div>
</template>

<script setup lang="ts">
// import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
// import dynamicRoutes from "@/mock/_data/system_menu";
import { Modal, Message } from "@arco-design/web-vue";
import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { getProjectAPI, deleteprojectAPI } from "@/api/modules/project/index";
import { getDictBycodeAPI, getDictBycode2API } from "@/api/modules/dictionary/index";
import { useUserInfoStore } from "@/store/modules/user-info";
import { onMounted, ref } from "vue";
const router = useRouter();
onMounted(() => {
  getDictBycodeAPIfun();
  getDictBycodeAPIfun2();
  getInit();
  init();
});
const serachValue = ref("");
const treeNodes = ref([]);

function projectshuxSet(e) {
  router.push({
    path: "/project/projectTab", query: {
      id: e.id,
      cq_equip_code: e.cq_equip_code
    }
  });
}

function InputEvent() {
  if (serachValue.value) {
    treeNodes.value = [];
    let arr = [];
    for (let i = 0; i < optionData.value.length; i++) {
      if (optionData.value[i].name.includes(serachValue.value)) {
        arr.push(optionData.value[i])
      }
    }
    treeNodes.value = generateTreeNodes(arr);
  } else {
    let obj = {}
    getAllqiyeAPI(obj).then(res => {
      treeNodes.value = generateTreeNodes(res.data);
    })
  }
}

const optionData = ref([])
async function getInit() {
  let obj = {};
  let res = await getAllqiyeAPI(obj);
  if (res.status == 2) {
    treeNodes.value = generateTreeNodes(res.data);
    optionData.value = res.data;
  }
}

const options558 = ref([]);
async function getDictBycodeAPIfun2() {
  let res = await getDictBycodeAPI(558);
  if (res.status == 2) {
    options558.value = res.data;
  }
}

function format558(val) {

  for (let i = 0; i < options558.value.length; i++) {
    if (options558.value[i].dictionary_name == val) {
      return options558.value[i].name
    }
  }

}
function formatqiye(val) {

  for (let i = 0; i < optionData.value.length; i++) {
    if (optionData.value[i].id == val) {
      return optionData.value[i].name
    }
  }

}
function generateTreeNodes(data) {
  const nodeMap = new Map();
  const rootNodes = [];

  // First pass: create nodes and store them in a map
  data.forEach(item => {
    const node = {
      id: item.id,
      name: item.name ? item.name : item.cq_company_short_name,
      children: [],
      data: item // Store all original data
    };
    nodeMap.set(item.cq_company_code, node);
  });

  // Second pass: build the tree structure
  data.forEach(item => {
    const node = nodeMap.get(item.cq_company_code);
    if (item.cq_parent_code === "0") {
      rootNodes.push(node);
    } else {
      const parentNode = nodeMap.get(item.cq_parent_code);
      if (parentNode) {
        parentNode.children.push(node);
      } else {
        console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
        rootNodes.push(node); // Add to root if parent not found
      }
    }
  });

  return rootNodes;
}

function clickTreeNode(selectedKeys, extra) {
  const allIds = [];
  getAllChildrenIds(extra.node, allIds);
  formData.form.scene_ids = allIds;

  init();
}

function getAllChildrenIds(node, idsArray) {
  // 把当前节点的 id 加入数组
  idsArray.push(node.id); // 如果有子节点，则递归处理
  if (node.children && node.children.length > 0) {
    node.children.forEach(child => {
      getAllChildrenIds(child, idsArray);
    });
  }
}
const total = ref(0);
async function init() {
  let res = await getProjectAPI(formData, formData.form);
  total.value = 0
  tableData.value = [];
  if (res.status == 2) {
    total.value = res.data.totalCount;
    tableData.value = res.data.data;
  }
}
function changePage(page) {
  formData.paged = page;
  init();
}
const tableData = ref([]);
const formData = reactive({
  form: {
    name: "",
    scene_id: "",
    scene_ids: []
  },
  paged: 1,
  pageSize: 10
});

const formRef = ref();
const onReset = () => {
  formRef.value.resetFields();
  init();
};

async function onSearch() {
  init();
}

const options81 = ref([]);
async function getDictBycodeAPIfun() {
  // let obj={}
  let res = await getDictBycodeAPI(81);
  if (res.status == 2) {
    options81.value = res.data;
  }
}

function clickName(val: any) {
  changeType(val);
  let stores = useUserInfoStore();
  stores.setSharedObject(val);

  let obj = options81.value.filter(e => {
    return (e.id = val.id);
  });

  val.iot_node_name = obj[0].name;

  router.push({ path: "/project/projectDetail" });
}

const options300 = ref([]);

async function changeType(val) {
  if (val.iot_node_type == 83) {
    let res = await getDictBycodeAPI(300);
    if (res.status == 2) {
      options300.value = res.data;
    }
  } else if (val.iot_node_type == 84) {
    let res = await getDictBycode2API(305);
    if (res.status == 2) {
      options300.value = res.data;
    }
  }
  let obj2 = options300.value.filter(e => {
    return (e.dictionary_name = val.iot_protocal_category);
  });
  val.iot_protocal_name = obj2[0].name;
}

function onAdd() {
  let stores = useUserInfoStore();
  stores.removeSharedObject();
  router.push({ path: "/project/projectAdd" });
}

const onEdit = (row: any) => {
  let stores = useUserInfoStore();
  stores.setSharedObject(row);
  router.push({ path: "/project/projectAdd" });
};

const onDelete2 = (row: any) => {
  Modal.warning({
    title: "提示",
    content: "确定删除？",
    hideCancel: false,
    closable: true,
    onOk: async () => {
      try {
        let res = (await deleteprojectAPI(row.id)) as any;
        if (res.status == 2) {
          Message.success("删除成功");
        } else {
          Message.error(res.statusMsg);
        }
        init();
      } catch { }
    }
  });
};
</script>

<style lang="scss">
.arco-modal-body {
  text-align: center !important;
}

.marquee {
  white-space: nowrap;
  /* 确保文本在一行内显示 */
  overflow: hidden;
  /* 隐藏溢出的内容 */
  text-overflow: ellipsis;
  /* 使用打点显示溢出的文本 */
  width: 100%;
  /* 设置宽度，根据需要调整 */
  max-width: 200px;
  /* 最大宽度，根据需要调整 */

  box-sizing: border-box;
  /* 防止宽度计算包含边框和内边距 */
}
</style>
